const vscode = require('vscode');
const GameServers = require('./GameServers');
const { user32, traverseMenu, executeMenuCommand } = require('./functions/window_api');

/**
 * @typedef {{ id:number, text: string, level:number, pid:number, children?:MenuInfo[] }} MenuInfo
 */

class MirMenu {

    /** @type {vscode.ExtensionContext} */
    context = null;

    /** @type { GameServers.ServerProcess} */
    serverProcess = null

    /**
     * 
     * @param {vscode.ExtensionContext} context 
     * @param {GameServers.ServerProcess} serverProcess 
     */
    constructor(context, serverProcess) {
        this.context = context;
        this.serverProcess = serverProcess
        this.getMirMenu()
    }


    getMirMenu() {
        if (!this.serverProcess) {
            return
        }
        const hwnd = this.serverProcess.windows.main.hwnd
        const menu = user32.GetMenu(hwnd);
        if (!menu) {
            return
        }
        const menulist = traverseMenu(menu)
        function findLoadMenus(list) {
            for (const item of list) {
                if (item.text.startsWith("重新加载")) {
                    return item.children
                }
                if (item.children) {
                    return findLoadMenus(item.children)
                }
            }
        }

        function loadFunctionMatchs(list) {
            const rules = [
                {
                    id: -1,
                    name: "QManage", label: "登录脚本",
                    menu: [/QManage|登录脚本/i],
                    file: [/Mir200\\Envir\\MapQuest_Def\\QManage([^\\]*)\.txt/]
                },
                {
                    id: -1,
                    name: "QFunction", label: "功能脚本",
                    menu: [/QFunction|功能脚本/i],
                    file: [/Mir200\\Envir\\Market_Def\\QFunction([^\\]*)\.txt/]
                },
                {
                    id: -1,
                    name: "QMission", label: "任务脚本",
                    menu: [/QMission|任务脚本/i],
                    file: [/Mir200\\Envir\\Market_Def\\QMission([^\\]*)\.txt/]
                },
                {
                    id: -1,
                    name: "QChatbox", label: "聊天框脚本",
                    menu: [/QChatbox|聊天框脚本/i],
                    file: [/Mir200\\Envir\\Market_Def\\QChatbox([^\\]*)\.txt/]
                },
                {
                    id: -1,
                    name: "Robot", label: "机器人脚本",
                    menu: [/Robot|机器人脚本/i],
                    file: [/Mir200\\Envir\\Robot_def\\.+\.txt/]
                },
                {
                    id: -1,
                    name: "NPC", label: "NPC脚本",
                    menu: [/所有NPC/i],
                    file: [
                        /Mir200\\Envir\\Market_Def\\.+\.txt/,
                        /Mir200\\Envir\\Npc_Def\\.+\.txt/,
                        /Mir200\\Envir\\QuestDiary\\.+\.txt/,
                        /Mir200\\Envir\\MerChant.txt/
                    ]
                },
            ]
            list.forEach(item => {
                rules.filter(rule => {
                    return rule.menu.some(reg => reg.test(item.text))
                }).map(v => v.id = item.id)
            });
            return rules
        }

        this.saveLoadRules = loadFunctionMatchs(findLoadMenus(menulist))



        const mirMenuProvider = new MirMenuTreeDataProvider(this.context, menulist)
        vscode.window.registerTreeDataProvider('extension.mir-script-plugin.MirMenu', mirMenuProvider);
        vscode.commands.registerCommand(mirMenuProvider.commandHeavyLoad, (id) => executeMenuCommand(hwnd, [id]))
        vscode.commands.registerCommand("extension.mir-config.showMirMenu", () => {
            vscode.commands.executeCommand("extension.mir-script-plugin.MirMenu.focus").then(() => {
                vscode.commands.executeCommand("list.expand")
            })


            // 创建快速选择器
            const quickPick = vscode.window.createQuickPick();
            quickPick.placeholder = "输入数字或关键词筛选指令";

            /**
                * @param {ReturnType<traverseMenu>} list 
                * @returns {vscode.QuickPickItem[]}
                */
            function filterMenus(valueArr, list, parentTitle = []) {
                /** @type {vscode.QuickPickItem[]} */
                const result = []
                for (let index = 0; index < list.length; index++) {
                    const parent = JSON.parse(JSON.stringify(parentTitle))
                    if (index === 0) {
                        result.push({
                            label: parent.join(" - "),
                            kind: vscode.QuickPickItemKind.Separator
                        })
                    }
                    const item = list[index];
                    if (item.children && item.children.length > 0) {
                        parent.push(item.text)
                        result.push(...filterMenus(valueArr, item.children, parent))
                        continue
                    }
                    if (!item.text) {
                        continue
                    }
                    const textArr = item.text.toLowerCase().split('');
                    const is = valueArr.every(v => {
                        const index = textArr.indexOf(v)
                        if (index !== -1) {
                            textArr.splice(index, 1)
                            return true
                        }
                        return false
                    })
                    if (is || item.id == parseInt(value)) {
                        result.push({
                            label: item.text,
                            description: `#${item.id}`,
                            alwaysShow: true,
                            source: item,
                        })
                    }
                }
                return result
            }

            // 动态更新选项列表
            quickPick.onDidChangeValue(value => {
                const valueArr = value.toLowerCase().split('');
                quickPick.items = filterMenus(valueArr, menulist)
            });

            // 处理选择确认
            quickPick.onDidAccept(() => {
                const selection = quickPick.selectedItems[0];
                if (selection) {
                    executeMenuCommand(hwnd, [selection.source.id])
                }
                quickPick.hide();
            });

            // 初始加载全部选项
            quickPick.items = filterMenus([], menulist)
            quickPick.show();
        })
    }



}

/**
 * 
 */
class MirMenuTreeDataProvider {
    commandHeavyLoad = "extension.mir-config.heavyLoad"
    /** 
     * @param {vscode.ExtensionContext} context  
     * @param {MenuInfo[]} list 
    */
    constructor(context, list = []) {
        this.context = context;
        this.list = list;
    }

    getChildren(element) {
        if (element) {
            return element.children.filter(e => !!e.text);
        }
        return this.list;
    }

    getTreeItem(element) {
        const treeItem = new vscode.TreeItem();
        treeItem.label = element.text;
        if (!element.children) {
            treeItem.command = { arguments: [element.id], command: "extension.mir-config.heavyLoad" }
            treeItem.collapsibleState = vscode.TreeItemCollapsibleState.None;
        } else {
            treeItem.collapsibleState = vscode.TreeItemCollapsibleState.Collapsed;
        }
        return treeItem;
    }

    refresh() {
        this.changeEvent.fire();
    }
}


module.exports = { MirMenuTreeDataProvider, MirMenu };